<?php
namespace Api\Service;

/**
 * 评论
 */
class ReviewService
{
    // 每页记录数
    const PAGET_NUMBER = 10;

    /**
     * 商品评论信息
     * @param  [type]  $goods_id [description]
     * @param  integer $page     [description]
     * @return [type]            [description]
     */
    public function goods($goods_id, $cur_page = 1)
    {
        $count = $this->getGoodsReviewCount($goods_id);

        if ($count) {
            $page = ceil($count / self::PAGET_NUMBER);
            $data = $this->getGoodsReview($goods_id, $cur_page);
        }

        return [
            'count'    => intval($count),
            'cur_page' => $cur_page,
            'page'     => $page ? $page : 0,
            'data'     => $data ? $data : [],
        ];
    }

    /**
     * 获取商品评论
     * @param  [type] $goods_id [description]
     * @return [type]           [description]
     */
    public function getGoodsReview($goods_id, $page = 1)
    {
        $where = ['r.goods_id' => $goods_id];

        $reviews = M('review')->alias('r')
            ->field('r.id,u.id user_id,u.avatar,u.username,r.content,r.spec_item,r.add_time')
            ->join('__USER__ u on r.user_id = u.id')
            ->where($where)
            ->page($page, self::PAGET_NUMBER)
            ->select();

        foreach ($reviews as $key => $review) {

            $image = M('review_image')
                ->where([
                    'review_id' => $review['id'],
                ])->getField('image', true);

            $reviews[$key]['image'] = $image ? $image : [];
        }

        return $reviews ? $reviews : [];
    }

    /**
     * 获取商品评论数量
     * @param  [type] $goods_id [description]
     * @return [type]           [description]
     */
    public function getGoodsReviewCount($goods_id)
    {
        $where = ['goods_id' => $goods_id];

        $count = M('review')->where($where)->count();

        return $count ? $count : 0;
    }

    /**
     * 获取商品评论数量
     * @param  [type] $goods_id [description]
     * @return [type]           [description]
     */
    public function getGoodsReviewPage($goods_id)
    {
        $where = ['goods_id' => $goods_id];

        $count = M('review')->where($where)->count();

        return $count ? $count : 0;
    }
}
